<template>
  <div id="order-apply-page" :style="{
    minHeight:(this.getWinSize().height-this.getSafeArea().top-45)+'px'
  }" v-if="productList.length>0">
    <div class="page-title"
         :style="{top:(this.getSafeArea().top)+'px'}">
      <div id="back-button" @click="$router.back()">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <span>商品退换货</span>
      <div class="button-box" :style="{
        top:(this.getSafeArea().top-3)+'px'
      }">
      </div>
    </div>

    <!--商品信息-->
    <div class="product-box"
         style="position: relative;"
         :style="{top:(this.getSafeArea().top)+'px'}"
    >
      <div class="item" v-for="(product,index) in productList" :key="index" :class="{curr:productNumsMap[product.shopProductStockId]>0}">
        <div class="image">
          <img :src="product.productImage"/>
        </div>
        <div class="right">
          <div class="name">
            <span class="ovd_s" v-text="product.productName"></span>
          </div>
          <div class="model-nums">
            <span class="model" v-text="'型号:'+product.productModel"></span>
            <span class="price red b" v-text="'商品金额:'+ToMoney(product.productPrice)"></span>
            <span class="nums red b" v-text="orderApply.type.name+'-数量: '+product.applyNums"></span>
          </div>
        </div>
        <div class="c"></div>
      </div>
    </div>

    <!--初始化提交表单-->
    <div class="init-form"
         style="position: relative;"
         :style="{top:(this.getSafeArea().top)+'px'}"
         v-if="orderApply.id>0">
      <el-form ref="form" :model="initForm" label-width="80px" size="small">
        <el-form-item label="类型:">
          <span v-text="orderApply.type.name"></span>
        </el-form-item>
        <el-form-item label="退货金额:" v-if="initForm.type!==1">
          <span class="red b" v-text="'￥'+ToMoney(orderApply.money)"></span>
        </el-form-item>
        <el-form-item label="退货理由:">
          <span v-text="initForm.reason"></span>
        </el-form-item>
      </el-form>
    </div>

    <!--步骤信息-->
    <div class="item" v-if="currStep>0"
         style="position: relative;"
         :style="{top:(this.getSafeArea().top)+'px'}"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in backStepList"
          :key="index"
          size="large"
          :timestamp="activity.createdAt"
          :class="getActiveClass(index)">
          <div class="step-content" @click="showInfo(index)" :class="isShowStep(index)">
            <div v-if="!activity.content">{{ (index + 1) + '.' + activity.tagName }}</div>
            <div v-if="activity.content">{{ (index + 1) + '.' + activity.tagName + '(' + activity.content + ')' }}</div>
            <el-button type="info" @click="showAddressInfo" style="position: absolute; right: -5px; top: 22px;" v-if="orderApply.status.id!==6 && index===1 && currStep>1 && initForm.type!==2">查看商家收货地址</el-button>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>



    <!--物流信息-->
    <div class="express-form" style="position: fixed; width: 100%; z-index: 9; height: 40px; line-height: 40px; bottom: 0px; padding-top: 0px; padding-bottom: 0px; margin: 0px; background: rgba(0,0,0,.5); border-radius: 0px;">
      <div align="center">
        <order-apply-act-button :curr-apply="orderApply" :call-back="getDetail"/>
      </div>

    </div>
  </div>
</template>

<script>
import AddressItem from '../common/AddressItem'
import OrderApplyActButton from '../common/OrderApplyActButton'
export default {
  name: 'OrderApplyDetail',
  components: {OrderApplyActButton, AddressItem},
  data: function () {
    return {
      productNumsMap:{},
      isGet:false,
      address:{},
      orderApply:{
        id:0,
        type:{id:-1},
        status:{id:-1},
      },
      applyId: 0,
      // 当前退货所处步骤
      currStep: -1,
      currBeforeStepName: '',
      // 显示初始提交信息
      showInitInfo: true,
      // 显示寄件信息
      showSendInfo: false,
      // 物流公司
      expressCompanyArr: dict.ExpressCompanyList,
      typeArr: dict.OrderApplyTypeArr,
      // 退回-物流-类型
      // 退货类型
      reasonArr: [
        '不想要了',
        '实物的外观,不太喜欢',
        '买多了,买错了',
        '临时不想要了',
        '太贵了',
      ],
      // 最大退款金额
      maxMoney:0,
      // 初次提交form
      initForm: {
        nums: 1,
        reason: '不想要了',
        money: 0,
        type: 0,
      },
      expressForm: {
        // 退回类型
        expressType: 0,
        expressCompany: '',
        expressNumber: '',
      },
      // 购买商品信息
      productList: [
        {
          "id": 4,
          "orderId": 4,
          "memberId": 18,
          "shopId": 7,
          "productId": 20,
          "productName": "百事可乐",
          "productImage": "http://image.yangfankj.com/product/7/0/0.png",
          "productPrice": 5,
          "productModel": "常规",
          "productNums": 3,
          "applyStatus": null,
          "commission": 1,
          "applyType": null,
          "applyId": 0,
          "score": null
        }
      ],
      // 标准退货步骤列表
      backStepList: [
        {
          content: '',
          tagName: '提交申请',
          createdAt: '2018-04-12 20:46'
        }, {
          content: '',
          tagName: '商家处理',
          createdAt: '-',
        }, {
          content: '',
          tagName: '用户寄件',
          createdAt: '-',
        }, {
          content: '',
          tagName: '商家收件',
          createdAt: '-'
        }]
    }
  },
  mounted () {
/*     if (this.$route.query.productData) {
      var product = JSON.parse(decodeURI(this.$route.query.productData))
      if (product.applyId > 0) {
        this.product = product
        this.applyId = product.applyId
        this.currStep = 1
        this.getDetail()
      } else {
        this.product = product
        this.initForm.nums = this.product.nums
        this.initForm.money = this.product.allPrice
        this.initForm.orderProductId = this.product.orderProductId
      }
    } */
    if (this.$route.query.isInit==1){
      this.getProductList()
    }else{
      this.bus.$emit('OpenOrderMessageCallBus','OrderApply_'+this.$route.query.id)
      this.getDetail()
    }
  },
  watch:{
    $route:function () {
      this.bus.$emit('OpenOrderMessageCallBus','OrderApply_'+this.$route.query.id)
      this.getDetail()
    }
  },
  methods: {
    showAddressInfo:function () {
      var addressInfo=this.orderApply.shopAddressInfo;
      var addressDetail=addressInfo.province+','+addressInfo.city+','+addressInfo.county+'  '+addressInfo.address;
      this.$alert('<div><div>收货人: '+addressInfo.name+','+addressInfo.mobile+'</div><div>'+addressDetail+'</div></div>', '商家退货地址', {
        dangerouslyUseHTMLString: true,
        // confirmButtonText: '确定',
        callback: action => {
        }
      });
    },
    // 获取-订单-商品列表(用于首次提交退换货)
    getProductList:function () {
      let $this=this
      $this.MyRequest($this.ApiDoNameShop + 'Order/getProductList', {orderId:$this.$route.query.orderId}, function (productList) {
        $this.productList=productList
        var productNumsForm={}
        var money=0
        productList.forEach(function (product,index) {
          money+=(product.productPrice*product.productNums).toFixed(2)-0
          // productNumsForm[product.shopProductStockId]=0
          productNumsForm[product.shopProductStockId]=product.productNums-0
        })
        $this.maxMoney=money
        $this.initForm.money=money
        $this.productNumsMap=productNumsForm
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 是否可撤销
    isCancel:function () {
      if (this.orderApply.type.id===0){
        return this.orderApply.status.id<3
      }
      if (this.orderApply.type.id===1){
        return this.orderApply.status.id<3
      }
    },
    // 合并当前操作记录 + 标准记录
    mergeStep: function (logList) {
      var stepArr = dict.OrderApplyStepNameArr[this.initForm.type]
      // console.log('stepArr',stepArr)
      var backStepList = []
      logList.forEach(function (log, _index) {
        var stepItem = {
          content: log.content,
          tagName: log.tagName,
          createdAt: log.createdAt,
          isComplete: log.isComplete,
        }
        /* stepArr.forEach(function (stepName, index) {
          if (log.tagName === stepName) {
            stepItem.createdAt = log.createdAt
            stepItem.content = log.content
          }
        }) */
        backStepList.push(stepItem)
      })

      this.currStep=backStepList.length
      this.currBeforeStepName=backStepList[backStepList.length-1].tagName

      // 补充后续-空步骤
      var currStepIsComplete=backStepList[backStepList.length-1].isComplete
      if (currStepIsComplete!==1){
        stepArr.forEach(function (stepName, index) {
          var isAdd=false
          backStepList.forEach(function (value,_index) {
            if (stepName===value.tagName){
              isAdd=true
            }
          })
          if (!isAdd){
            backStepList.push({
              content: '',
              tagName: stepName,
              createdAt: '-'
            })
          }
        })
      }

      if (this.orderApply.status.id===6){
        backStepList=backStepList.slice(0,2)
      }
      if (this.orderApply.type.id===2){
        backStepList=backStepList.slice(0,2)
      }

      this.backStepList = backStepList
      this.$forceUpdate()
    },

    // 获取-退换货详情
    getDetail: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameShop + 'OrderApply/getDetail', {id: this.$route.query.id}, function (data) {
        $this.initForm.nums = data.nums
        $this.initForm.money = data.money
        $this.initForm.type = data.type.id
        $this.initForm.reason = data.reason
        $this.orderApply = data
        var productList=[]
        data.productData.forEach(function (item, index) {
          productList.push({
            productId:item.id,
            productName:item.name,
            productImage:item.image,
            productPrice:item.price,
            productModel:item.model,
            productNums:item.nums,
            applyNums:item.applyNums,
          })
        })
        $this.productList = productList
        $this.mergeStep(data.logList)

        if (data.status.id===1){
          $this.getDefaultAddress()
        }
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 获取-默认地址
    getDefaultAddress: function () {
      var $this = this
      var addressId = 0
      if ($this.$route.query.chooseAddressId) {
        addressId = $this.$route.query.chooseAddressId
      }
      $this.MyRequest($this.ApiDoNameShop + 'ShopAddress/getDetail', {id: addressId}, function (data) {
        if (data.id) {
          $this.address.id = data.id
          $this.address.name = data.name
          $this.address.province = data.province
          $this.address.city = data.city
          $this.address.county = data.county
          $this.address.mobile = data.mobile
          $this.address.address = data.address
          $this.address.isDefault = data.isDefault === 1
        }
        $this.isGet = true
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 是否显示当前步骤信息
    isShowStep: function (index) {
      if (index === 0) {
        return this.showInitInfo ? '' : ''
      }
      if (index === 2) {
        return this.showSendInfo ? '' : ''
      }
    },
    // 提交物流信息
    submitExpress: function () {
      let $this = this
      var form=Object.assign({},$this.expressForm)
      // 自送至店铺
      if (!form.expressCompany){
        return $this.successTip('快递公司 不能为空','warning')
      }
      if (!form.expressNumber){
        return $this.successTip('快递单号 不能为空','warning')
      }
      if (!$this.address || !$this.address.id){
        return $this.successTip('地址信息 不能为空','warning')
      }
      form.addressId=$this.address.id

      form.orderApplyId=$this.orderApply.id
      $this.MyRequest($this.ApiDoNameShop + 'OrderApply/submitExpressApply', form, function (data) {
        $this.successTip('提交成功!')
        $this.$router.push("OrderList")
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 显示操作过的信息: 0.初始提交,2.发件信息
    showInfo (index) {
      if (index === 0) {
        if (this.currStep === 0) {
          return
        }
        // this.showSendInfo = false
        // this.showInitInfo = !this.showInitInfo
      }
      if (index === 2) {
        if (this.currStep === 2) {
          return
        }
        this.showInitInfo = false
        this.showSendInfo = !this.showSendInfo
      }
    },
    calcMaxMoney:function () {
      let $this = this
      var currMaxMoney=0
      $this.productList.forEach(function (product, index) {
        var nums=$this.productNumsMap[product.shopProductStockId]
        currMaxMoney+=(nums*product.productPrice).toFixed(2)-0
      })
      $this.initForm.money=currMaxMoney
      $this.maxMoney=currMaxMoney
    },
    // 初始提交
    submit: function () {
      let $this = this
      var money=$this.initForm.money
      var shopStockIds = Object.keys($this.productNumsMap)
      var orderProductNumsMapList=[]
      shopStockIds.forEach(function (shopStockId, index) {
        if ($this.productNumsMap[shopStockId]>0){
          orderProductNumsMapList.push({
            shopProductStockId:shopStockId,
            nums:$this.productNumsMap[shopStockId],
          })
        }
      })
      if (orderProductNumsMapList.length===0){
        return $this.successTip('退货数量必须大于: 0','warning')
      }
      if ($this.initForm.type!==1){
        if (money<=0.01){
          return $this.successTip('最小退款金额为: 0.01','warning');
        }
      }else{
        money=0
      }
      if (money>$this.maxMoney){
        return $this.successTip('退款金额不能超过: '+$this.maxMoney,'warning');
      }
      var form={
        orderId:$this.$route.query.orderId,
        orderProductNumsMapList:JSON.stringify(orderProductNumsMapList),
        money:money,
        type:$this.initForm.type,
        reason:$this.initForm.reason,
      }
      $this.MyRequest($this.ApiDoNameShop + 'OrderApply/submit', form, function (data) {
        $this.successTip('提交成功!')
        $this.$router.back()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
      })
    },
    // 获取状态标记类
    getActiveClass: function (index) {
      if (index < this.currStep) {
        return 'over'
      } else if (index === this.currStep) {
        return 'curr'
      } else {
        return ''
      }
    },
    // 换货确认收货
    receivedApply:function () {
      let $this = this
      $this.$confirm('您是否确认进行该操作?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.MyRequest($this.ApiDoNameShop + 'OrderApply/receivedApply', {orderApplyId:$this.orderApply.id}, function (data) {
          $this.successTip('收货成功!')
          $this.$router.back()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    },
    // 撤销申请
    cancel: function () {
      let $this = this
      $this.$confirm('您是否确认进行该操作?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.MyRequest($this.ApiDoNameShop + 'OrderApply/cancelApply', {orderApplyId:$this.orderApply.id}, function (data) {
          $this.successTip('撤销成功!')
          $this.$router.back()
          $this.$forceUpdate()
        }, function (msg) {
          $this.$message.error(msg)
        })
      })
    }
  }
}
</script>

<style scoped>
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{ margin-bottom: 10px}
</style>
